<?php

namespace App\Http\Controllers\Web\V1;

use App\Http\Controllers\Controller;
use App\Models\Question;
use App\Models\Redo;
use Dingo\Api\Http\Response;
use Exception;
use Illuminate\Http\Request;
use League\Fractal\TransformerAbstract;

class RedoController extends Controller
{

    /**
     * 获取错题数量 'radio', 'checkbox', 'judge', 'fill', 'short', 'subsystem' 错题的类型
     * @return Response
     */
    public function index()
    {
        return $this->response->array([
            'checkbox' => userQuestionCount('checkbox'),
            'radio' => userQuestionCount('radio'),
            'judge' => userQuestionCount('judge'),
            'fill' => userQuestionCount('fill'),
            'short' => userQuestionCount('short'),
            'subsystem' => userQuestionCount('subsystem'),
        ]);
    }


    /**
     * 获取错题列表详情
     *
     * type 可以是 radio checkbox blanks judge short_answer
     * @return Response
     */
    public function list($type)
    {
        $question_id = Redo::query()
            ->where('user_id', $this->adminUser()->id())
            ->where('type', $type)
            ->pluck('question_id')
            ->toArray();

        $questions = Question::query()
            ->whereIn('id', $question_id)
            ->select('id', 'content', 'success_answer', 'answer', 'type')
            ->paginate($this->pageLimit());

        return $this->response->paginator($questions, new class extends TransformerAbstract {
            public function transform(Question $question)
            {
                return [
                    'id' => $question->id,
                    'type' => $question->type,
                    'content' => $question->content,
                    'answer' => $question->answer,
                    'success_answer' => $question->success_answer,
                ];
            }
        });

    }

    /**
     * 错题重做
     * @param Request $request
     * @param Redo $redo
     * @return Response
     */
    public function restart(Request $request, Redo $redo)
    {
        $request->validate([
            'answer' => 'required',
            'id' => 'required|exists:questions,id'
        ]);

        $request->offsetSet('fraction', 0);

        $data = autoCorrect($request->all());

        if ($data['is_true'] == false) {
            return $this->response->array($data);
        }

        $redo->delete();

        return $this->response->array($data);

    }


    /**
     * 移除错题
     * @param Redo $redo
     * @return Response
     * @throws Exception
     */
    public function delete(Redo $redo)
    {
        $redo->delete();

        return $this->response->noContent();
    }
}
